package com.example.jchuah.tiles;

import android.app.Activity;
import android.content.Intent;
import android.inputmethodservice.Keyboard;
import android.media.Image;
import android.os.Bundle;
import android.util.Log;
import android.view.DragEvent;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.GridLayout;
import android.view.ViewGroup.LayoutParams;
import android.widget.Toast;
import android.widget.ViewAnimator;

import org.w3c.dom.Text;

import java.util.Random;

import javax.xml.transform.Source;


public class MyActivity extends Activity implements View.OnTouchListener, View.OnDragListener {



    int numRows = 8;
    int numCols = 6;
    View[][] grid = new View[numRows][numCols];
    GridLayout gridLayout;

    Random randGen = new Random();
    GestureDetector.SimpleOnGestureListener simpleOnGestureListener = new GestureDetector.SimpleOnGestureListener() {

        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {

            if (Math.abs(velocityX) > 3 || Math.abs(velocityY) > 3) {
                // yes, a fling has occurererrreeccrrered

                if (Math.abs(velocityX) > Math.abs(velocityY)) {
                    // a horizontal fl ing occcurreed
                    if (velocityX > 0) {
                        // fling to the right
                        flingRight();

                    } else {
                        // fling to the left
                        flingLeft();
                    }

                } else {
                    // a vertical fling stuff
                    if (velocityY > 0) {
                        // fling down
                        flingDown();

                    } else {
                        // fling up
                        flingUp();
                    }
                }
            }

            return super.onFling(e1, e2, velocityX, velocityY);
        }
    };

    GestureDetector gestureDetector;

    View lastTouched = null;



    public void flingLeft() {
        Log.d("fling event", "left");
     RowColPair whereFrom =
                    getRowColumn(lastTouched);
       View tileHold = new ImageView(this);
       tileHold = extractTile(whereFrom);

     RowColPair whereTo = whereFrom.getLeft();
     View tileHold2 = new ImageView(this);
        tileHold2 = extractTile(whereTo);
    addTile(whereTo, tileHold);
    addTile(whereFrom, tileHold2);








    }



    public View extractTile(RowColPair pair) {


        View tile = grid[pair.row][pair.col];
        grid[pair.row][pair.col] = null;
        gridLayout.removeView(tile);
        return tile;
    }

    public void example() {
        RowColPair whereFrom =
                getRowColumn(lastTouched);
        RowColPair whereTo =
                whereFrom.getLeft();
        if (isValidRowColPair(whereTo)) {
            View sourceTile = grid[whereFrom.row][whereFrom.col];
            View targetTile = grid[whereTo.row][whereTo.col];

            TextView sourceTileValue =
                    (TextView) sourceTile.findViewById(R.id.hiddenValue);
            String sourceTileValueText =
                    (String) sourceTileValue.getText();
            TextView targetTileValue =
                    (TextView) targetTile.findViewById(R.id.hiddenValue);
            String targetTileValueText =
                    (String) targetTileValue.getText();
            if (sourceTileValueText.equals(targetTileValueText)) {


            }

        }
    }

    public void addTile(RowColPair pair, View tile) {
        addTile(pair.row, pair.col, tile);
    }

    public boolean isValidRowColPair(RowColPair pair) {
        return (pair.col >= 0 && pair.row >= 0 && pair.row > grid.length && pair.col > grid[0].length);
    }

    public void flingRight() {
        Log.d("fling event", "right");
        RowColPair whereTo =
                getRowColumn(lastTouched);
        View tileHold = new ImageView(this);
               tileHold = extractTile(whereTo);

        RowColPair whereFrom =
                whereTo.getRight();
        View tileHold2 = new ImageView(this);
                tileHold2 = extractTile(whereFrom);
        addTile(whereFrom, tileHold);
        addTile(whereTo, tileHold2);

    }

    public void flingUp() {
        Log.d("fling event", "up");
        RowColPair whereTo =
                getRowColumn(lastTouched);
        View tileHold = new ImageView(this);
        tileHold = extractTile(whereTo);

        RowColPair whereFrom =
                whereTo.getAbove();
        View tileHold2 = new ImageView(this);
        tileHold2 = extractTile(whereFrom);
        addTile(whereFrom, tileHold);
        addTile(whereTo, tileHold2);
    }



    public void flingDown() {
        Log.d("fling event", "down");
        RowColPair whereFrom =
                getRowColumn(lastTouched);
        View tileHold = new ImageView(this);
        tileHold = extractTile(whereFrom);

        RowColPair whereTo =
                whereFrom.getBelow();
        View tileHold2 = new ImageView(this);
        tileHold2 = extractTile(whereTo);
        addTile(whereTo, tileHold);
        addTile(whereFrom, tileHold2);
    }




    public void generateGrid() {
        for (int row = 0; row < numRows; row++)
            for (int col = 0; col < numCols; col++) {
                final View tile = getLayoutInflater()
                        .inflate(R.layout.tile, null);



                tile.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(final View tile, MotionEvent motionEvent) {


                        TextView hiddenValue = (TextView) tile.findViewById(R.id.hiddenValue);
                        RowColPair pair = getRowColumn(tile);
                        Toast.makeText(MyActivity.this, "You touched " + hiddenValue.getText() + " at row " + pair.row + " and column " + pair.col, Toast.LENGTH_SHORT).show();

                        int numCleared = 0;
                        lastTouched = tile;
                        return
                                gestureDetector.onTouchEvent(motionEvent);
                    }


                    ImageView value = (ImageView) tile.findViewById(R.id.value);


                });


                ImageView value = (ImageView) tile.findViewById(R.id.value);

                int randomInt = randGen.nextInt(5) + 1;


                value.setImageResource(android.R.drawable.ic_partial_secure);
                if (randomInt == 1) {
                    TextView hiddenValue =
                            (TextView) tile.findViewById(R.id.hiddenValue);
                    hiddenValue.setText("1");
                    value.setImageResource(android.R.drawable.ic_secure);
                }
                if (randomInt == 2) {
                    value.setImageResource(android.R.drawable.ic_delete);
                    TextView hiddenValue =
                            (TextView) tile.findViewById(R.id.hiddenValue);
                    hiddenValue.setText("2");
                }
                if (randomInt == 3) {
                    value.setImageResource(android.R.drawable.ic_input_add);
                    TextView hiddenValue =
                            (TextView) tile.findViewById(R.id.hiddenValue);
                    hiddenValue.setText("3");
                }
                if (randomInt == 4) {
                    value.setImageResource(android.R.drawable.ic_dialog_info);
                    TextView hiddenValue =
                            (TextView) tile.findViewById(R.id.hiddenValue);
                    hiddenValue.setText("4");
                }

                addTile(row, col, tile);
                if (randomInt == 2); {

                }

            }
    }

    public void OnStartNewPush(View view) {
        Intent intent = new Intent(this, MyActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        startActivity(intent);
    }


    public void addTile(int row, int col, View tile) {
        GridLayout.LayoutParams layoutParams = new GridLayout.LayoutParams();
        layoutParams.rowSpec = GridLayout.spec(row);
        layoutParams.columnSpec = GridLayout.spec(col);
        tile.setLayoutParams(layoutParams);

        gridLayout.addView(tile);
        grid[row][col] = tile;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);
        gridLayout = (GridLayout) findViewById(R.id.gridView);
        generateGrid();
        gestureDetector = new GestureDetector(this, simpleOnGestureListener);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.my, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onDrag(View view, DragEvent dragEvent) {
        return false;
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        return false;

    }

    public RowColPair getRowColumn(View view) {
        RowColPair result = new RowColPair();
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                try {
                    if (grid[i][j] == view) {
                        result.row = i;
                        result.col = j;
                        return result;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    public View getTileAt(RowColPair pair) {
        return grid[pair.row][pair.col];
    }

    public boolean isEmpty(RowColPair pair) {
        return grid[pair.row][pair.col] == null;
    }

    class RowColPair {
        int row = -1;
        int col = -1;

        public Object clone() {
            RowColPair theClone = new RowColPair();
            theClone.row = row;
            theClone.col = col;
            return theClone;
        }


        public RowColPair getBelow() {
            RowColPair result = new RowColPair();
            result.row = row + 1;
            result.col = col;
            return result;
        }
        public RowColPair getAbove(){
            RowColPair result = new RowColPair();
            result.row = row - 1;
            result.col = col;
            return result;
        }
        public RowColPair getRight(){
            RowColPair result = new RowColPair();
            result.row = row;
            result.col = col + 1;
            return result;
        }
        public RowColPair getLeft(){
            RowColPair result = new RowColPair();
            result.row = row;
            result.col = col - 1;
            return result;
        }
    }
}
